package com.getpebble.android.framework.install;

import android.content.Context;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ThreadUtil;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.Response;
import com.koushikdutta.ion.builder.Builders.Any.B;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FileDownloadManager {
    private static final String TAG = FileDownloadManager.class.getSimpleName();
    private final Context mContext;
    private final String mDirectory;

    public FileDownloadManager(Context context, String directory) {
        this.mContext = context;
        this.mDirectory = directory;
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    }

    public String downloadFile(String uri) {
        byte[] fileBytes = fetchFile(uri);
        if (fileBytes != null) {
            return writeFile(getFileFromUri(uri), fileBytes);
        }
        Trace.error(TAG, "downloadFile: fileBytes was null.");
        return null;
    }

    public boolean deleteFile(String uri) {
        File file = getFileFromUri(uri);
        if (file.exists()) {
            return file.delete();
        }
        return true;
    }

    public File getFile(String filename) {
        return new File(this.mContext.getDir(this.mDirectory, 0), filename);
    }

    public File getFileFromUri(String uri) {
        return getFile(removeTrailingQueryString(getFilenameFromUri(uri)));
    }

    private String removeTrailingQueryString(String fileName) {
        return fileName.split("\\?")[0];
    }

    private String getFilenameFromUri(String uri) {
        String[] parts = uri.split("/");
        return parts[parts.length - 1];
    }

    private String writeFile(File pbzFile, byte[] bytes) {
        try {
            OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pbzFile));
            outputStream.write(bytes);
            outputStream.close();
            return pbzFile.getName();
        } catch (FileNotFoundException e) {
            Trace.error(TAG, "Unable to write to file.", e);
            return null;
        } catch (IOException e2) {
            Trace.error(TAG, "Unable to write bytes.", e2);
            return null;
        }
    }

    public byte[] fetchFile(String uri) {
        try {
            ThreadUtil.logAssertOnMainThread(TAG, "fetchFile");
            Response<byte[]> response = (Response) ((B) Ion.with(this.mContext).load(uri)).asByteArray().withResponse().get(60000, TimeUnit.MILLISECONDS);
            if (response == null) {
                Trace.warning(TAG, "response is null");
                return null;
            } else if (response.getHeaders() == null) {
                Trace.warning(TAG, "response getHeaders() is null");
                Trace.debug(TAG, "response result = " + response.getResult());
                return null;
            } else if (response.getHeaders().getResponseCode() == 200) {
                return (byte[]) response.getResult();
            } else {
                Trace.error(TAG, "Unexpected response code: " + response.getHeaders().getResponseCode());
                return null;
            }
        } catch (InterruptedException ie) {
            Trace.error(TAG, "Interrupted while fetching file.", ie);
            return null;
        } catch (ExecutionException ee) {
            Trace.error(TAG, "Exception while fetching file.", ee);
            return null;
        } catch (TimeoutException e) {
            Trace.error(TAG, "Exception while fetching file.", e);
            return null;
        }
    }
}
